package a09_JUC;

import java.util.concurrent.TimeUnit;

/**
 * @Author quan
 * @Description 死锁
 * @Date 2023/5/22 15:41
 */
public class a08_DeadLock {
    /**
     * 演示两个线程获取两把锁，陷入死锁中。没看懂这个怎么死锁的过程，看代码也执行结束了。不清楚为啥这样写代码。
     * @param args
     */
    public static void main(String[] args) {
        //1、定义两个锁对象
        Object lock1 = new Object();
        Object lock2 = new Object();
        //2、线程1，先获取lock1，再获取lock2
        Thread t1 = new Thread(()->{
            System.out.println("t1申请lock1");
            //3、获取lock1
            synchronized (lock1){
                System.out.println("t1申请到了lock1");
                //模拟业务处理过程
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            //4、获取lock2
                System.out.println("t1申请到lock2");
                synchronized (lock2){
                    System.out.println("t1获取到了两把锁资源");
                }
            }
        });
        //5、启动线程1
        t1.start();
        //线程2：先获取lock2，再获取lock1
        Thread t2 = new Thread(()->{
            System.out.println("t2申请lock2");
            //3、获取lock1
            synchronized (lock1){
                System.out.println("t2申请到了lock2");
                //模拟业务处理过程
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //4、获取lock2
                System.out.println("t2申请到lock2");
                synchronized (lock2){
                    System.out.println("t1获取到了两把锁资源");
                }
            }
        });
        //启动线程
        t2.start();
    }
}
